<?php
namespace app\index\controller;
use app\common\model\Category;
use app\common\model\Goodsattribute;
use houdunwang\arr\Arr;
use app\common\model\Goods as GoodsModel;
use houdunwang\Cart;
use think\Db;

class Goods extends Common
{
    public function index(Category $category)
    {
//        $cartdata = $this->category();
        $cdata = db('category')->limit(5)->select();
        $field = Arr::channelLevel(db('category')->where('id>5')->select(), $pid = 0, $html = "&nbsp;", $fieldPri = 'id', $fieldPid = 'pid');
        $id = input ('id');
        //halt($id);
        #根据id处理面包屑导航(递归找父级)
        $Fdata = $this->getFdata($category, $id);
        //获取对应的商品数据
        $Gdata = GoodsModel::get($id);
//        halt($Gdata);
        $Adata = Goodsattribute::get(['goods_id'=>$id]);
//        halt($Gdata);
        #查询商品图片表预览图
        $picdata = $Gdata->goods_pic;
//        halt($picdata);
        #查询商品属性表
        $atribute = $Gdata->goods_attribute;
//        halt($atribute);
//        dump();die;

        if (input('pic'))
        {
            $id = input('pic');
            $picdata = Db::table('goodspic')->where('attributeid',$id)->select();
        }
        #查询商品属性表关联图片表, 查出每个颜色对应的图片
//        $picdata = $Adata->goodspic;
//        dump($picdata);
        return $this->template('goods',compact('field','data','cdata','Gdata','picdata','atribute','Fdata','cartdata'));
    }
    /**
     * 获得所有父级栏目
     * @param $category
     * @param $id
     * @return array
     *
     */
    public function getFdata($category,$id)
    {
        $data = db('category')->select();
//        halt($data);
        $Fdata = $category->getFatherData($data,$id);
        #将数组反转
//         halt($Fdata);
        return array_reverse($Fdata);
    }
    public function ajaxAddCart()
    {
        $post = $_POST;
//        halt($post);
        $goodsdata = db('goods')->where('id',$post['id'])->field('title,price,list_pic')->find();
        $data =[
            'id' =>$post['id'],
            'name' => $goodsdata['title'],
            'num' => $post['num'],
            'price' => $goodsdata['price'],
            'options' =>[
                'color' =>$post['spec']['color'],
                'size' =>$post['spec']['size'],
                'img' =>$goodsdata['list_pic'],
            ]
        ];
//        halt($data);
        $cart = new Cart();
        $cart->add($data);
        echo 1;
    }
    public function ajaxPic()
    {
        $data ='';
        $id = $_POST['aid'];
        $data1 = Db::table('goodspic')->where('attributeid',$id)->select();
        foreach ($data1 as $k =>$v)
        {
            $data1['nu'] = $v['pic'];
        }





        return($data1) ;
    }
}
